package me.qi.kancha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.qi.kancha.dto.core.EntityRoleDTO;
import me.qi.kancha.dto.core.RoleRuleDTO;
import me.qi.kancha.dto.core.RuleDTO;
import me.qi.kancha.mapper.RuleMapper;
import me.qi.kancha.service.EntityRoleService;
import me.qi.kancha.service.RoleRuleService;
import me.qi.kancha.service.RuleService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author sun
* @description 针对表【rule】的数据库操作Service实现
* @createDate 2022-01-05 10:54:18
*/
@Service
public class RuleServiceImpl extends ServiceImpl<RuleMapper, RuleDTO>
    implements RuleService {

    private final EntityRoleService entityRoleService;

    private final RoleRuleService roleRuleService;

    public RuleServiceImpl(EntityRoleService entityRoleService, RoleRuleService roleRuleService) {
        this.entityRoleService = entityRoleService;
        this.roleRuleService = roleRuleService;
    }

    @Override
    public List<RuleDTO> list(String parent) {
        QueryWrapper wrapper = new QueryWrapper();
        if (!ObjectUtils.isEmpty(parent)) {
            wrapper.eq("parent", parent);
        } else {
            wrapper.isNull("parent");
        }
        return list(wrapper);
    }

    @Override
    public List<String> codes(String entityId) {
        List<String> ids = new ArrayList<>();
        ids.add(entityId);
        return getRuleCodes(ids);
    }

    /**
     * 根据主体查询权限
     *
     * @param ids
     * @return
     */
    private List<String> getRuleCodes(List<String> ids) {
        List<String> rules = new ArrayList<>();
        //查询角色
        LambdaQueryWrapper<EntityRoleDTO> entityRoleWrapper = new LambdaQueryWrapper<>();
        List<EntityRoleDTO> entityRoleList = entityRoleService.list(entityRoleWrapper.in(EntityRoleDTO::getEntityId, ids));
        if (!entityRoleList.isEmpty()) {
            //查询角色关联权限
            List<String> roles = entityRoleList.stream().map(EntityRoleDTO::getRoleCode).collect(Collectors.toList());
            LambdaQueryWrapper<RoleRuleDTO> roleRuleWrapper = new LambdaQueryWrapper<>();
            List<RoleRuleDTO> roleRuleDTOS = roleRuleService.list(roleRuleWrapper.in(RoleRuleDTO::getRoleCode, roles));
            if (!roleRuleDTOS.isEmpty()) {
                rules = roleRuleDTOS.stream().map(RoleRuleDTO::getRuleCode).collect(Collectors.toList());
            }
        }
        return rules;
    }
}




